//
// Created by lenovo on 24-9-1.
//

#include "seqlist.h"

// 对数据的管理:增删查改
void SeqListInit(SeqList* ps)
{
    int i = 0;
    ps->size = 10;
    for(i=0; i<ps->size; i++)
    {
        ps->a[i] = (SLDateType)malloc(sizeof(SLDateType));
    }
}

void SeqListDestroy(SeqList* ps)
{
    free(ps->a);
    ps->a = NULL;
    ps->capacity = ps->size = 0;
}

void SeqListPrint(SeqList* ps)
{
    int i = 0;
    for(i=0; i<ps->size; i++)
    {
        printf("%d->",ps->a[i]);
    }
}

void SeqListCheck(SeqList *ps)
{
    if(ps->size == ps->capacity)
    {
        SLDateType *tmp = (SLDateType*)realloc(ps->a,sizeof(SLDateType)*ps->capacity*2);
        if(tmp == NULL)
        {
            perror("realloc fail");
            return;
        }
        ps->a = tmp;
        ps->capacity *= 2;
    }
}

void SeqListPushBack(SeqList* ps, SLDateType x)
{
    SeqListCheck(ps);
    ps->a[ps->size++] = x;
}

void SeqListPushFront(SeqList* ps, SLDateType x)
{
    assert(ps);
    SeqListCheck(ps);
    int end = ps->size-1;
    while(end >= 0)
    {
        ps->a[end+1] = ps->a[end];
        end--;
    }
    ps->a[0] = x;
    ps->size++;
}

void SeqListPopFront(SeqList* ps)
{
    assert(ps);
    assert(ps->size>0);

    int begin = 0;
    while(begin<ps->size)
    {
        ps->a[begin] = ps->a[begin+1];
        begin++;
    }
    ps->size--;
}
void SeqListPopBack(SeqList* ps)
{
    assert(ps->size>0);
    ps->size--;
}

// 顺序表查找
int SeqListFind(SeqList* ps, SLDateType x)
{
    assert(ps);
    int i = 0;
    for(i=0; i<ps->size; i++)
    {
        if(ps->a[i]==x)
        {
            return i;
        }
    }
    return -1;
}
// 顺序表在pos位置插入x
void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
    assert(ps);
    assert(pos >= 0 && pos <=ps->size);

    SeqListCheck(ps);
    int end = ps->size-1;
    while(end >=pos)
    {
        ps->a[end+1] = ps->a[end];
        end--;
    }
    ps->a[pos] = x;
    ps->size++;
}
// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, int pos)
{
    assert(ps);
    assert(pos >=0 && pos <= ps->size);

    int begin = pos+1;
    while(begin<ps->size)
    {
        ps->a[begin-1] = ps->a[begin];
        begin++;
    }
    ps->size--;
}